package com.example.fw;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateHelper extends HelperBase {	// Hibernate - Object Relation Mapper

	public HibernateHelper(ApplicationManager manager) {
		super(manager);
	}

	public Groups getGroups() {
		//Groups groups = null;
		//Session session = null; 
		//session = HibernateUtil.getSessionFactory().openSession();
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction t = session.beginTransaction();
		try {
			return new Groups((List<GroupObject>) session.createQuery("from GroupObject").list());
		} finally {
			t.commit();
		}
//		if (session != null && session.isOpen()) {
//			session.close();
//		}
	}

	public String getNextGroupId() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		//return session.createQuery("SELECT AUTO_INCREMENT FROM information_schema.TABLES").uniqueResult().toString();
		return session.createSQLQuery("SELECT AUTO_INCREMENT FROM information_schema.TABLES where TABLE_SCHEMA = 'addressbook' and TABLE_NAME = 'group_list'").uniqueResult().toString();
		//return session.createQuery("select max(id) from GroupObject").uniqueResult().toString();
	}
	
	public Contacts getContacts() {
		//session = HibernateUtil.getSessionFactory().openSession();
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction t = session.beginTransaction();
//		try {
			return new Contacts((List<ContactObject>) session.createQuery("from ContactObject").list());
//		} finally {
//			t.commit();
//		}
	}

	public String getNextContactId() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		return session.createSQLQuery("SELECT AUTO_INCREMENT FROM information_schema.TABLES where TABLE_SCHEMA = 'addressbook' and TABLE_NAME = 'addressbook'").uniqueResult().toString();
	}

	public ContactObject getDbContactData(String modifiedContactId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction t = session.beginTransaction();
		try {
			return new ContactObject((ContactObject) session.createQuery("from ContactObject where id="+ modifiedContactId).list());
		} finally {
			t.commit();	// ?
		}
	}
}